import random
import time

from selenium.common import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait

from comment.write_excle import excel_append
from compements.assemblies.introducing_medication import introducing_medication
from compements.tool import update_exercise_time, update_staple_food, diabetes_assessment, hypertension_assessment
from tool1 import *

def new_follow_up(driver, new_sf_data, sfzh, record, headers, filtered_hypertension, filtered_diabetes, filtered_combined,sf_time,name):
    if "随访方式" in headers:
        sf_method = record['随访方式']
    else:
        sf_method = "门诊"

    driver.switch_to.default_content()

    WebDriverWait(driver, 10).until(
        ec.presence_of_element_located((By.XPATH, "//li[contains(text(),'慢病随访')]"))).click()
    time.sleep(1)

    # 切换到第一个 iframe
    first_iframe = WebDriverWait(driver, 10).until(
        ec.presence_of_element_located((By.XPATH, '//*[@id="ext-gen21"]/iframe')))
    driver.switch_to.frame(first_iframe)

    # 切换到第二个 iframe
    second_iframe = WebDriverWait(driver, 10).until(
        ec.presence_of_element_located((By.XPATH, '//*[@id="ext-gen32"]/iframe')))
    driver.switch_to.frame(second_iframe)

    element = WebDriverWait(driver, 10).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="document_title"]/tbody/tr/td[3]/img')))
    element.click()
    time.sleep(3)

    # 获取慢病类型
    element = WebDriverWait(driver, 10).until(
        ec.presence_of_element_located((By.XPATH, '//*[@id="divOne_1"]/tbody/tr[2]/td/input[1]')))
    mb_type = element.get_attribute('value')

    # 获取其他慢病类型
    element = WebDriverWait(driver, 10).until(
        ec.presence_of_element_located((By.XPATH, '//*[@id="divOne_1"]/tbody/tr[2]/td/input[4]')))
    other_mb_type = element.get_attribute('value')

    # 获取人群分类
    element = WebDriverWait(driver, 10).until(
        ec.presence_of_element_located((By.XPATH, '//*[@id="divOne_1"]/tbody/tr[1]/td/input[4]')))
    mb_group = element.get_attribute('value')

    # 随访日期
    follow_date = WebDriverWait(driver, 10).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="dateCreated"]')))
    driver.execute_script("arguments[0].removeAttribute('readonly');", follow_date)
    follow_date.click()
    follow_date.clear()
    follow_date.send_keys(new_sf_data['随访日期'])

    # 是否加入国家标准版
    WebDriverWait(driver, 10).until(
        ec.presence_of_element_located((By.XPATH,
                                        "//td[contains(text(),'是否加入国家标准版')]//input[@name='isGj' and @value='1']"))).click()
    time.sleep(.5)
    # 随访方式
    wait = WebDriverWait(driver, 10)  # 等待最多10秒
    select_element = wait.until(ec.visibility_of_element_located((By.XPATH, '//*[@id="followWay"]')))
    select = Select(select_element)
    select.select_by_visible_text(sf_method)

    # 无症状处理
    sentences = {}
    if "高血压" in mb_type and "糖尿病" not in mb_type:
        # 高血压患者适用 (15句)
        sentences = filtered_hypertension
        # sentences = {
        #     1: "患者无头晕、视物模糊等不适，按时服药，未出现药物不良反应，血压稳定，饮食作息有规律。",
        #     2: "患者无耳鸣、视物模糊等症状，定期服药，无药物副作用，血压稳定，生活起居规律。",
        #     3: "患者无头痛、眩晕等不适，服药规律，无药物过敏反应，血压保持平稳，生活作息有条不紊。",
        #     4: "患者无四肢乏力、胸痛等不适，按时服用降压药，未出现不良反应，血压控制理想，作息正常。",
        #     5: "患者无浮肿、乏力等症状，遵医嘱服药，未出现药物副作用，血压控制平稳，饮食搭配合理。",
        #     6: "患者无呼吸困难、咳嗽等不适，定期服药，无药物不耐受，血压保持平稳，生活起居规律。",
        #     7: "患者无头晕、恶心等不适，按时服用降压药，无药物副作用，血压控制在目标范围内，作息健康。",
        #     8: "患者无胸痛、心悸等症状，遵医嘱用药，无药物不耐受反应，血压保持良好，饮食睡眠有规律。",
        #     9: "患者无便秘、腹胀等不适，按时服用降压药，未出现副作用，血压维持在正常水平，饮食睡眠正常。",
        #     10: "患者无肢体麻木、心慌等不适，规律用药，无药物相关不适主诉，血压控制平稳，日常活动正常。",
        #     11: "患者无失眠、烦躁等症状，坚持服药治疗，未诉不良反应，血压管理有效，精神状态良好。",
        #     12: "患者无颈部僵硬、耳鸣等主诉，用药依从性好，无特殊不适，血压维持稳定，生活自理能力正常。",
        #     13: "患者无胸闷、气短等不适，规范进行药物治疗，耐受性良好，血压控制达标，日常活动无受限。",
        #     14: "患者无疲劳感、注意力不集中等症状，长期服药无异常反应，血压水平平稳，社会功能正常。",
        #     15: "患者无鼻出血、面部潮红等表现，持续用药无不适，血压长期稳定，生活质量保持良好。"
        # }
    elif "糖尿病" in mb_type and "高血压" not in mb_type:
        # 糖尿病患者适用 (15句)
        sentences = filtered_diabetes
        # sentences = {
        #     1: "患者无口干、多饮等症状，遵医嘱服药，无药物副作用，血糖波动不大，饮食规律。",
        #     2: "患者无多饮、多尿等症状，遵医嘱服药，无药物过敏现象，血糖监测平稳，作息规律。",
        #     3: "患者无腹痛、腹胀等不适，按时服用降糖药，未出现副作用，血糖控制在正常范围，作息良好。",
        #     4: "患者无手足麻木、四肢无力等症状，服药依从性好，无药物不良反应，血糖管理较好，作息稳定。",
        #     5: "患者无头晕、视物模糊等症状，服药规律，无药物过敏反应，血糖水平平稳，饮食习惯良好。",
        #     6: "患者无恶心、呕吐等症状，服药依从性良好，无明显药物不良反应，血糖水平正常，饮食健康。",
        #     7: "患者无消化不良、食欲下降等不适，服药依从性良好，无药物过敏反应，血糖控制理想，饮食睡眠良好。",
        #     8: "患者无皮疹、瘙痒等症状，服药规律，无不良反应，血糖管理得当，饮食清淡，作息正常。",
        #     9: "患者无四肢乏力、胸痛等不适，按时服用降糖药，未出现不良反应，血糖保持稳定，生活规律。",
        #     10: "患者无晕厥、乏力等症状，按时服药，未出现药物不耐受反应，血糖保持稳定，睡眠充足。",
        #     11: "患者无皮肤感染、伤口不易愈合等情况，持续用药无异常，血糖控制有效，日常活动正常。",
        #     12: "患者无体重异常下降、多食等症状，规范治疗无不适反应，血糖监测平稳，营养状况良好。",
        #     13: "患者无足部麻木、刺痛等感觉异常，长期服药耐受性好，血糖水平稳定，行动能力正常。",
        #     14: "患者无尿频、尿急等泌尿系症状，坚持治疗未诉不良反应，血糖管理达标，生活自理良好。",
        #     15: "患者无视力变化、眼部不适等主诉，用药依从性高，无药物相关不适，血糖控制理想，生活质量良好。"
        # }
    elif "高血压" in mb_type and "糖尿病" in mb_type:
        # 高血压合并糖尿病患者适用 (15句)
        sentences = filtered_combined
        # sentences = {
        #     1: "患者无乏力、四肢麻木等不适，遵医嘱用药，无明显不良反应，血压和血糖控制稳定，睡眠质量较好。",
        #     2: "患者无恶心、呕吐等不适，服药依从性良好，未出现不良反应，血压和血糖控制良好，饮食习惯规律。",
        #     3: "患者无便秘、腹泻等症状，定期服药，无明显药物不良反应，血压和血糖保持平稳，睡眠情况正常。",
        #     4: "患者无头痛、眼花等不适，服药依从性高，未出现不良反应，血压和血糖保持平稳，生活作息有序。",
        #     5: "患者无头晕、视物模糊等不适，按时服药，未出现药物不良反应，血压和血糖保持在理想范围内，作息健康。",
        #     6: "患者无胸部不适、呼吸困难，服药规范，无药物不良反应，血压和血糖控制良好，睡眠状态佳。",
        #     7: "患者无四肢麻木、乏力等症状，按时服药，无药物副作用，血压和血糖控制在理想范围内，作息规律。",
        #     8: "患者无晕厥、恶心等症状，遵医嘱用药，无不良反应，血压和血糖控制较好，饮食清淡，作息正常。",
        #     9: "患者无头痛、眩晕等不适，服药规律，无药物不良反应，血压和血糖管理稳定，生活起居有条不紊。",
        #     10: "患者无乏力、头晕等症状，服药规律，无明显不良反应，血压和血糖保持在目标范围，作息健康。",
        #     11: "患者无心悸、多汗等不适，长期联合用药耐受性良好，血压血糖均稳定，日常活动不受限。",
        #     12: "患者无水肿、尿量异常等情况，规范治疗无药物副作用，血压血糖控制达标，生活自理能力正常。",
        #     13: "患者无皮肤感觉异常、口渴等主诉，坚持用药无不适反应，血压血糖监测平稳，精神状态良好。",
        #     14: "患者无胸闷、气促等症状，持续治疗未诉不良反应，血压血糖管理有效，社会功能保持正常。",
        #     15: "患者无失眠、焦虑等表现，双重用药依从性好，耐受性佳，血压血糖均控制理想，生活质量满意。"
        # }

    # random_hypertension_sentence = sentences[random.randint(1, 15)]
    random_key = random.choice(list(sentences.keys()))
    random_hypertension_sentence = sentences[random_key]

    """选择其他 填写无症状"""
    wait = WebDriverWait(driver, 10)
    checkbox = wait.until(ec.element_to_be_clickable((By.XPATH,
                                                      "//label[contains(text(), '其他')]/preceding-sibling::input")))

    if not checkbox.is_selected():
        checkbox.click()
        input_element = WebDriverWait(driver, 10).until(
            ec.visibility_of_element_located((By.XPATH, "//label[contains(text(), '其他')]/following-sibling::textarea")))

        time.sleep(1)

        # input_element.clear()
        # input_element.send_keys(random_hypertension_sentence)
        # 使用 JavaScript 填充文本框
        driver.execute_script("arguments[0].value = arguments[1];", input_element, random_hypertension_sentence)

    # """选择无症状"""
    # wait = WebDriverWait(driver, 10)
    # checkbox = wait.until(ec.element_to_be_clickable((By.XPATH,
    #                                                   "//label[contains(text(), '无症状')]/preceding-sibling::input")))
    #
    # if not checkbox.is_selected():
    #     checkbox.click()
    #     time.sleep(1)

    # 收缩压
    element = WebDriverWait(driver, 10).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="sbp"]')))
    element.clear()
    sbp = str(int(float(new_sf_data['收缩压'])))
    element.send_keys(sbp)

    # 舒张压 dbp
    element = WebDriverWait(driver, 10).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="dbp"]')))
    element.clear()
    dbp = str(int(float(new_sf_data['舒张压'])))
    element.send_keys(dbp)

    # 身高
    element = WebDriverWait(driver, 10).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="height"]')))
    element.clear()
    element.send_keys(new_sf_data['身高'])

    # 体重
    element = WebDriverWait(driver, 10).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="weightCur"]')))
    element.clear()
    element.send_keys(new_sf_data['体重'])

    # 目标体重
    element = WebDriverWait(driver, 10).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="bmiCur"]')))
    bmi = element.get_attribute('value')
    bmi = float(bmi)

    target_weight = new_sf_data['体重']
    if bmi >= 24:
        target_weight = float(new_sf_data['体重']) - float(random.randint(1, 2))
    elif bmi < 18.5:
        target_weight = float(new_sf_data['体重']) + float(random.randint(1, 2))
    elif bmi >= 28:
        target_weight = float(new_sf_data['体重']) - float(random.randint(2, 3))
    target_weight = str(round(float(target_weight), 1))
    element = WebDriverWait(driver, 10).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="weightTar"]')))
    element.clear()
    element.send_keys(target_weight)

    # 心率
    try:
        element = WebDriverWait(driver, 3).until(
            ec.visibility_of_element_located((By.XPATH, '//*[@id="heartRateCur"]')))
        element.clear()
        element.send_keys(new_sf_data['心率'])

        # 目标心率
        element = WebDriverWait(driver, 3).until(
            ec.visibility_of_element_located((By.XPATH, '//*[@id="heartRateTar"]')))
        element.clear()
        element.send_keys(random.randint(60,99))
    except:
        pass

    # 其他体征
    element = WebDriverWait(driver, 10).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="otherSign"]')))
    element.clear()
    waist = new_sf_data['腰围']
    other_signs = f'腰围:{waist}cm,双下肢未见水肿'
    element.send_keys(other_signs)

    # 日吸烟量
    element = WebDriverWait(driver, 10).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="smAmountCur"]')))
    element.clear()
    element.send_keys(new_sf_data['日吸烟量'])

    target_smoke_amount = "0"
    # 目标日吸烟量
    # if int(new_sf_data['日吸烟量']) >= 1:
    #     target_smoke_amount = int(new_sf_data['日吸烟量']) - 1
    # target_smoke_amount = str(target_smoke_amount)

    element = WebDriverWait(driver, 10).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="smAmountTar"]')))
    element.clear()
    element.send_keys(target_smoke_amount)

    # 日饮酒量
    element = WebDriverWait(driver, 10).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="dkAmountCur"]')))
    element.clear()
    element.send_keys(new_sf_data['日饮酒量'])

    # 目标日饮酒量
    target_drink_amount = "0"
    # if int(new_sf_data['日饮酒量']) >= 5:
    #     target_drink_amount = int(new_sf_data['日饮酒量']) - random.randint(2, 3)
    # target_drink_amount = str(target_drink_amount)
    element = WebDriverWait(driver, 10).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="dkAmountTar"]')))
    element.clear()
    element.send_keys(target_drink_amount)

    # 运动次数
    element = WebDriverWait(driver, 10).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="exCycleCur"]')))
    element.clear()
    element.send_keys(new_sf_data['运动次数'])

    # 目标运动次数
    target_sport_times = 7
    if int(new_sf_data['运动次数']) < 7:
        target_sport_times = 7
    target_sport_times = str(target_sport_times)

    element = WebDriverWait(driver, 10).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="exCycleTar"]')))
    element.clear()
    element.send_keys(target_sport_times)

    # 运动时间
    element = WebDriverWait(driver, 10).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="exTimeCur"]')))
    element.clear()
    element.send_keys(new_sf_data['运动时间'])

    # 目标运动时间
    # target_sport_time = update_exercise_time(sfzh, new_sf_data['运动时间'], bmi)
    target_sport_time = new_sf_data['运动时间']
    if new_sf_data['运动时间'] <= 30:
        target_sport_time = 30

    element = WebDriverWait(driver, 10).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="exTimeTar"]')))
    element.clear()
    element.send_keys(target_sport_time)
    new_sf_data["运动时间"] = target_sport_time

    # 主食量
    try:
        element = WebDriverWait(driver, 3).until(
            ec.visibility_of_element_located((By.XPATH, '//*[@id="fhAmountCur"]')))
        element.clear()
        element.send_keys(new_sf_data['主食量'])

        # 目标主食量
        target_fh_amount = update_staple_food(bmi, new_sf_data['主食量'])
        element = WebDriverWait(driver, 3).until(
            ec.visibility_of_element_located((By.XPATH, '//*[@id="fhAmountTar"]')))
        element.clear()
        element.send_keys(target_fh_amount)
    except:
        pass

    # 空腹血糖
    element = WebDriverWait(driver, 10).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="fbg"]')))

    with open("./执行结果/env.txt", 'r', encoding='utf-8') as file:
        content = file.readlines()
    # 使用 split() 方法分割字符串
    place = content[6].replace("：", ":").split(":")[1]
    place = place.strip()
    print("无糖尿病是否录入空腹血糖:", place)
    if place == "否":
        element.clear()
        # 方法1：直接执行JS清空并触发事件（推荐）
        js_script = """
            var input = document.getElementById('fbg');
            input.value = '';
            // 创建并触发keyup事件
            var event = new Event('keyup');
            input.dispatchEvent(event);
        """
        driver.execute_script(js_script)
        # 执行JS清空隐藏输入框的值
        driver.execute_script("document.getElementById('fbg_hidden').value = '';")
    if place == '是':
        element.clear()
        element.send_keys(new_sf_data['空腹血糖'])
    if "糖尿病" in mb_type:
        element.clear()
        element.send_keys(new_sf_data['空腹血糖'])

    # 餐后血糖
    try:
        element = WebDriverWait(driver, 3).until(
            ec.visibility_of_element_located((By.XPATH, '//*[@id="pbg"]')))
        element.clear()
        element.send_keys("未查")
    except:
        pass

    # 糖化血红蛋白
    try:
        element = WebDriverWait(driver, 3).until(
            ec.visibility_of_element_located((By.XPATH, '//*[@id="hba1c"]')))
        element.clear()
        element.send_keys("未查")

        element = WebDriverWait(driver, 3).until(
            ec.visibility_of_element_located((By.XPATH, '//*[@id="hba1cDate"]')))
        element.clear()
    except:
        pass

    # TC
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="tc"]'))).clear()
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="tc"]'))).send_keys('未查')

    # TG
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="tg"]'))).clear()
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="tg"]'))).send_keys('未查')

    # HDL-C
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="hdlC"]'))).clear()
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="hdlC"]'))).send_keys(
        '未查')

    # LDL-C
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="ldlC"]'))).clear()
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="ldlC"]'))).send_keys(
        '未查')

    # BUN
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="bun"]'))).clear()
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="bun"]'))).send_keys(
        '未查')

    # Cr
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="cr"]'))).clear()
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="cr"]'))).send_keys('未查')

    # 肌酐清除率
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="ccr"]'))).clear()
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="ccr"]'))).send_keys(
        '未查')

    # 尿检
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="uran"]'))).clear()
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="uran"]'))).send_keys(
        '未查')

    # 尿微量白蛋白
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="malb"]'))).clear()
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="malb"]'))).send_keys(
        '未查')

    # 心电图
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="ecg"]'))).clear()
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="ecg"]'))).send_keys(
        '未查')

    # 眼底
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="fundusOculi"]'))).clear()
    WebDriverWait(driver, 10).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="fundusOculi"]'))).send_keys('未查')

    # 其他辅助检查
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="otherTest"]'))).clear()
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="otherTest"]'))).send_keys(
        '未查')

    # 是否咳嗽、咳痰≥2周
    WebDriverWait(driver, 10).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="isCough2"]'))).click()
    time.sleep(.5)

    # 是否痰中带血或咯血
    WebDriverWait(driver, 10).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="isHemoptysis2"]'))).click()
    time.sleep(.5)

    # 评估
    pg = ''
    # if '高血压' in mb_type:
    #     pg = pg + '高血压（血压控制满意）' + ','
    # if '糖尿病' in mb_type:
    #     pg = pg + '糖尿病（血糖控制满意）' + ','

    # 患者姓名
    people_element = WebDriverWait(driver, 10).until(
            ec.visibility_of_element_located((By.XPATH, '//*[@id="divOne_1"]/tbody/tr[1]/td/input[1]')))
    people_name = people_element.get_attribute('value')
    print("患者姓名：", people_name)

    # 随访人
    doctor_element = WebDriverWait(driver, 10).until(
            ec.visibility_of_element_located((By.XPATH, '//*[@id="followPerson"]')))
    doctor_name = doctor_element.get_attribute('value')
    print("随访人：", doctor_name)

    if '高血压' in mb_type:
        # 判断血压是否控制满意
        hypertension_result = hypertension_assessment(dbp, sbp, sfzh, new_sf_data['随访日期'], people_name, doctor_name)
        pg = pg + hypertension_result + ','
        if hypertension_result == "高血压（血压控制不满意）":
            print("高血压（血压控制不满意）")
            if '高血压' in mb_type and '糖尿病' not in mb_type:
                element = WebDriverWait(driver, 10).until(ec.visibility_of_element_located((
                    By.XPATH, '//*[@id="divOne_1"]/tbody/tr[4]/td/label[2]')))
                driver.execute_script("arguments[0].scrollIntoView();", element)
                driver.execute_script("arguments[0].click();", element)
            elif '高血压' in mb_type and '糖尿病' in mb_type:
                element = WebDriverWait(driver, 10).until(ec.visibility_of_element_located((
                    By.XPATH, '//*[@id="divOne_1"]/tbody/tr[4]/td/label[2]')))
                driver.execute_script("arguments[0].scrollIntoView();", element)
                driver.execute_script("arguments[0].click();", element)

    if '糖尿病' in mb_type:
        diabetes_result = diabetes_assessment(new_sf_data['空腹血糖'], sfzh, new_sf_data['随访日期'], people_name, doctor_name)
        pg = pg + diabetes_result + ','
        if diabetes_result == "糖尿病（血糖控制不满意）":
            print("糖尿病（血糖控制不满意）")
            if '高血压' not in mb_type and '糖尿病' in mb_type:
                element = WebDriverWait(driver, 10).until(ec.visibility_of_element_located((
                    By.XPATH, '//*[@id="divOne_1"]/tbody/tr[4]/td/label[2]')))
                driver.execute_script("arguments[0].scrollIntoView();", element)
                driver.execute_script("arguments[0].click();", element)
            elif '高血压' in mb_type and '糖尿病' in mb_type:
                element = WebDriverWait(driver, 10).until(ec.visibility_of_element_located((
                    By.XPATH, '//*[@id="divOne_1"]/tbody/tr[5]/td/label[2]')))
                driver.execute_script("arguments[0].scrollIntoView();", element)
                driver.execute_script("arguments[0].click();", element)

    if '冠心病' in mb_type or '冠心病' in other_mb_type:
        pg = pg + '冠心病（控制平稳）' + ','
    if "脑卒中" in mb_type or '脑卒中' in other_mb_type:
        pg = pg + '脑卒中（控制平稳）' + ','

    if int(sfzh[16]) % 2 == 0:
        gender = '女'
    else:
        gender = '男'

    if 24 <= bmi < 28:
        pg = pg + '超重' + ','
    if bmi >= 28:
        pg = pg + '肥胖' + ','

    if waist != '':
        the_waist = float(waist)
        if gender == '女':
            if the_waist >= 85:
                pg = pg + '腹型肥胖' + ','
        elif gender == '男':
            if the_waist >= 90:
                pg = pg + '腹型肥胖' + ','


    if new_sf_data['日吸烟量'] != 0:
        pg = pg + '吸烟' + ','
    if new_sf_data['日饮酒量'] != 0:
        pg = pg + '饮酒' + ','


    if new_sf_data['运动次数'] == 0 or new_sf_data['运动时间'] == 0 or new_sf_data['运动次数']*new_sf_data['运动时间'] < 150:
        pg = pg + '缺乏体育锻炼' + ','

    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="assess"]'))).clear()
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="assess"]'))).send_keys(pg)

    advice_items = []

    # 根据pg内容生成个性化生活指导建议（随机选择，控制总数在8-15个）
    pg_related_advices = []

    # 根据pg中的问题生成针对性建议
    if '高血压（血压控制不满意）' in pg:
        pg_related_advices.append('血压管理：每日定时测量血压，低盐饮食（<5g/日），避免情绪激动')

    if '糖尿病（血糖控制不满意）' in pg:
        pg_related_advices.append('血糖管理：定时监测血糖，控制碳水化合物摄入，注意足部护理')

    if '超重' in pg or '肥胖' in pg:
        pg_related_advices.append('体重管理：控制热量摄入，增加有氧运动，目标每周减重0.5-1公斤')

    if '腹型肥胖' in pg:
        pg_related_advices.append('腹型肥胖干预：重点减少内脏脂肪，增加核心肌群训练')

    if '吸烟' in pg:
        pg_related_advices.append('戒烟干预：采用"5D戒烟法"，寻求专业戒烟门诊帮助')

    if '饮酒' in pg:
        pg_related_advices.append('限酒指导：男性<25克酒精/日，女性<15克酒精/日')

    if '缺乏体育锻炼' in pg:
        pg_related_advices.append('运动处方：从快走开始，逐步增加至每周150分钟中等强度运动')

    # 原有建议分类
    existing_advices = {
        '戒烟建议': [],
        '控制饮酒': [],
        '饮食调节': [],
        '运动建议': [],
        '老年人专项': [],
        '健康管理': [],
        '用药指导': [],
        '卫生防疫': []
    }

    # 填充各个类别
    if new_sf_data['日吸烟量'] != 0:
        existing_advices['戒烟建议'].append(
            '建议采用"5D戒烟法"：Delay（延迟吸烟）、Deep breathing（深呼吸）、Drink water（喝水）、Do something（转移注意）、Discuss（寻求支持）')

    if new_sf_data['日饮酒量'] != 0:
        xb = WebDriverWait(driver, 10).until(
            ec.presence_of_element_located((By.XPATH, '//*[@id="divOne_1"]/tbody/tr[1]/td/input[2]'))).text
        alcohol_advice = {
            '男': '建议控制饮酒量（25克酒精≈啤酒750ml/葡萄酒250ml/白酒75ml），避免混合饮酒',
            '女': '建议控制饮酒量（15克酒精≈啤酒450ml/葡萄酒150ml/白酒50ml），经期孕期禁酒'
        }
        existing_advices['控制饮酒'].append(alcohol_advice.get(xb, '建议减少酒精摄入'))

    if '无偏好' not in mb_group:
        existing_advices['饮食调节'].extend([
            '饮食建议：每日盐摄入<5g，烹调油25-30g',
            '优质蛋白选择：鱼虾禽类＞畜肉，每周至少2次深海鱼',
            '膳食纤维摄入：每日25-30g（如燕麦、杂豆、绿叶菜）',
            '烹饪方式建议：蒸煮炖优于煎炸烤'
        ])

    if '残疾人' not in mb_group:
        if new_sf_data['运动时间'] == 0:
            existing_advices['运动建议'].append('运动建议：从每天10分钟快走开始，每周递增5分钟')
        elif bmi >= 24:
            existing_advices['运动建议'].extend([
                '有氧运动：每周5次，每次30分钟（快走、游泳、骑行）',
                '抗阻训练：每周2-3次（弹力带、深蹲）',
                '核心训练：每天5分钟平板支撑'
            ])

    if '老年人' in mb_group:
        existing_advices['老年人专项'].extend([
            '防跌倒措施：居家安装扶手，穿防滑鞋',
            '骨质疏松预防：每日钙摄入1000-1200mg+维生素D800IU',
            '认知训练：每日脑力活动（阅读、棋牌）30分钟'
        ])

    existing_advices['健康管理'].extend([
        '睡眠管理：保证7-8小时/天，避免睡前使用电子设备',
        '心理调节：每日正念冥想10分钟',
        '环境健康：室内PM2.5＜37μg/m³，湿度40%-60%'
    ])

    existing_advices['用药指导'].append('用药管理：使用分药盒，设置服药提醒，注意药物相互作用（如阿司匹林与酒精）')

    existing_advices['卫生防疫'].extend([
        '手卫生：七步洗手法，接触公共物品后及时消毒',
        '环境通风：每日开窗3次，每次＞30分钟'
    ])

    # 从每个类别中随机选择建议项
    selected_advices = []

    # 首先添加所有pg相关的建议
    selected_advices.extend(pg_related_advices)

    # 然后从其他类别中随机选择建议项，控制总数


    # 计算还需要多少建议项（控制在8-15个之间）
    remaining_slots = max(8 - len(pg_related_advices), 0)  # 至少要包含所有pg相关建议
    if remaining_slots > 0:
        # 收集所有其他类别的建议
        other_advices = []
        for category_advices in existing_advices.values():
            other_advices.extend(category_advices)

        # 如果其他建议数量小于等于剩余位置，全部添加
        if len(other_advices) <= remaining_slots:
            selected_advices.extend(other_advices)
        else:
            # 如果超过剩余位置，随机选择
            selected_advices.extend(random.sample(other_advices, remaining_slots))

    # 如果总数仍少于8个，从所有建议中随机补充
    all_possible_advices = pg_related_advices[:]
    for category_advices in existing_advices.values():
        all_possible_advices.extend(category_advices)

    if len(selected_advices) < 8:
        needed = min(8 - len(selected_advices), len(all_possible_advices) - len(selected_advices))
        additional_advices = [advice for advice in all_possible_advices if advice not in selected_advices]
        if additional_advices:
            selected_advices.extend(random.sample(additional_advices, min(needed, len(additional_advices))))

    # 确保总数不超过15个
    if len(selected_advices) > 15:
        selected_advices = random.sample(selected_advices, 15)

    advice_items = selected_advices

    # 生成最终生活指导建议
    life_suggestions = '\n'.join([f'{i + 1}. {item}' for i, item in enumerate(advice_items)])

    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="lifestyle"]'))).clear()
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="lifestyle"]'))).send_keys(
        life_suggestions)



    # 医生建议
    doctor_advice = ''
    if "高血压" in mb_type and "糖尿病" not in mb_type:
        doctor_advice = generate_doctor_advice("高血压",pg)
    elif '糖尿病' in mb_type and "高血压" not in mb_type:
        doctor_advice = generate_doctor_advice("糖尿病",pg)
    elif "高血压" in mb_type and "糖尿病" in mb_type:
        doctor_advice = generate_doctor_advice("糖尿病",pg)
        doctor_advice = doctor_advice.replace("定期监测血糖、足背动脉","定期监测血糖、血压，足背动脉")
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="suggest"]'))).clear()
    WebDriverWait(driver, 10).until(ec.visibility_of_element_located((By.XPATH, '//*[@id="suggest"]'))).send_keys(
        doctor_advice)

    # 点击用药情况
    try:
        medication_element = WebDriverWait(driver, 3).until(
            ec.visibility_of_element_located((By.XPATH, '//font[contains(text(), "用  药  情  况")]')))
    except TimeoutException:
        medication_element = WebDriverWait(driver, 3).until(
            ec.visibility_of_element_located((By.XPATH, '//font[contains(text(), "用药情况")]')))
    driver.execute_script("arguments[0].click();", medication_element)
    time.sleep(1.5)

    try:
        element = WebDriverWait(driver, 5).until(
            ec.visibility_of_element_located((By.XPATH, '//span[contains(text(), "需要先")]')))
        print("需要先保存随访，才能引入用药")
        time.sleep(.5)
        yes_element = WebDriverWait(driver, 10).until(
            ec.visibility_of_element_located((By.XPATH, '//button[contains(text(), "是")]')))
        # driver.execute_script("arguments[0].click();", yes_element)
        driver.execute_script("""
            var element = arguments[0];
            var clickEvent = new MouseEvent('click', { bubbles: true });
            element.dispatchEvent(clickEvent);
            element.dispatchEvent(clickEvent);
        """, yes_element)

        try:
            # 获取本季度已做过慢病随访，是否继续保存
            with open("./执行结果/env.txt", 'r', encoding='utf-8') as file:
                content = file.readlines()
            # 使用 split() 方法分割字符串
            yes = content[5].replace("：", ":").split(":")[1].strip()

            element = WebDriverWait(driver, 3).until(
                ec.visibility_of_element_located((By.XPATH, "//span[contains(text(),'本季度已做过慢病随访')]")))
            print("获取本季度已做过慢病随访，是否继续保存:", yes)

            element_yes = WebDriverWait(driver, 3).until(
                ec.visibility_of_element_located((By.XPATH, f"//button[text()='{yes}']")))
            driver.execute_script("arguments[0].click();", element_yes)

            with open("./执行结果/本季度已做过慢病随访.txt", 'a+', encoding='utf-8') as a:
                a.write(f"{new_sf_data}-本季度已做过慢病随访，是否继续保存:{yes}\n")

            if yes == '否':
                return False, random_hypertension_sentence

        except TimeoutException:
            pass

        WebDriverWait(driver, 5).until(
            ec.visibility_of_element_located((By.XPATH, "//button[text()='确定']"))).click()
        try:
            element = WebDriverWait(driver, 5).until(
                ec.visibility_of_element_located((By.XPATH, '//span[contains(text(), "是否加入到个人服务计划中")]')))
            WebDriverWait(driver, 5).until(
                ec.visibility_of_element_located((By.XPATH, '//button[contains(text(), "否")]'))).click()
        except:
            pass
        # 点击用药情况
        try:
            medication_element = WebDriverWait(driver, 3).until(
                ec.visibility_of_element_located((By.XPATH, '//font[contains(text(), "用  药  情  况")]')))
        except TimeoutException:
            medication_element = WebDriverWait(driver, 3).until(
                ec.visibility_of_element_located((By.XPATH, '//font[contains(text(), "用药情况")]')))
        driver.execute_script("arguments[0].click();", medication_element)
    except:
        pass

    # 开始引入用药
    result = introducing_medication(driver, mb_type, new_sf_data, sfzh)
    if result is False or result == set():
        print(f"{sfzh}---没有引入任何药品")
        with open("./执行结果/没有引入任何药品.txt", 'a+', encoding='utf-8') as file:
            file.write(f"{sfzh}---没有引入任何药品\n")

    if result is False and sf_time == []:
        with open("./执行结果/没有引入任何药品.txt", 'a+', encoding='utf-8') as file:
            file.write(f"{sfzh}---没有引入任何药品,并且无今年的随访记录\n")
    time.sleep(1.5)

    # 点击保存
    save_button = WebDriverWait(driver, 30).until(
        ec.visibility_of_element_located((By.XPATH, '//*[@id="saveAction"]')))
    driver.execute_script("arguments[0].click();", save_button)

    try:
        # 获取本季度已做过慢病随访，是否继续保存
        with open("./执行结果/env.txt", 'r', encoding='utf-8') as file:
            content = file.readlines()
        # 使用 split() 方法分割字符串
        yes = content[5].replace("：", ":").split(":")[1].strip()

        element = WebDriverWait(driver, 3).until(
            ec.visibility_of_element_located((By.XPATH, "//span[contains(text(),'本季度已做过慢病随访')]")))
        print("获取本季度已做过慢病随访，是否继续保存:", yes)

        element_yes = WebDriverWait(driver, 3).until(
            ec.visibility_of_element_located((By.XPATH, f"//button[text()='{yes}']")))
        driver.execute_script("arguments[0].click();", element_yes)

        with open("./执行结果/本季度已做过慢病随访.txt", 'a+', encoding='utf-8') as a:
            a.write(f"{new_sf_data}-本季度已做过慢病随访，是否继续保存:{yes}\n")

        if yes == '否':
            return False, random_hypertension_sentence

    except TimeoutException:
        pass

    try:
        element = WebDriverWait(driver, 3).until(
            ec.visibility_of_element_located((By.XPATH, "//span[contains(text(),'药品名称不能为空或无')]")))
        WebDriverWait(driver, 3).until(
            ec.visibility_of_element_located((By.XPATH, "//button[text()='确定']"))).click()
        excel_append("执行结果/异常名单.xlsx", "身份证号", sfzh + '\t', "异常原因", "新建失败-药品名称不能为空或无无法保存","姓名", name)
        return False, random_hypertension_sentence
    except TimeoutException:
        pass

    try:
        element = WebDriverWait(driver, 120).until(
            ec.visibility_of_element_located((By.XPATH, "//span[contains(text(),'保存成功')]")))
        WebDriverWait(driver, 120).until(
            ec.visibility_of_element_located((By.XPATH, "//button[text()='确定']"))).click()
        print(f'{new_sf_data}-随访保存成功')
        excel_append("执行结果/成功名单.xlsx", '身份证号', sfzh, '成功', f"慢病随访新建成功-{new_sf_data}, 引入用药-{result}","姓名", name)
    except TimeoutException:
        print(f'{new_sf_data}-随访保存超时')
        excel_append("执行结果/异常名单.xlsx", "身份证号", sfzh + '\t', "异常原因", f"{new_sf_data}保存超时-需验证重跑","姓名", name)

    return False, random_hypertension_sentence









